import cloud from '@lafjs/cloud'
const db = cloud.mongo.db

export default {
  //时间格式转换
  dateTimeFormat(date, type?: String) {
    if (!date) return
    var d = new Date(date);
    d = d.getFullYear() > 0 ? d : new Date(Date.parse(date.replace(/-/g, "/")));        //为了兼容ios
    var year = d.getFullYear();
    var month = ('0' + (d.getMonth() + 1)).slice(-2);
    var day = ('0' + (d.getDate())).slice(-2);
    var hour = ('0' + (d.getHours())).slice(-2);
    var minutes = ('0' + (d.getMinutes())).slice(-2);
    var seconds = ('0' + (d.getSeconds())).slice(-2);
    switch (type) {
      case 'all':
        return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`
      case 'dayMinutes':
        return `${month}.${day} ${hour}:${minutes}`;
      case 'time':
        return `${hour}:${minutes}:${seconds}`
      case 'month':
        return Number(month)
      case 'year':
        return year
      case 'monthDate':
        return `${month}-${day}`;
      case 'yearMonth':
        return `${year}-${month}`;
      default:
        return `${year}-${month}-${day}`;
    }
  },

  //获取当前时间
  getNowInUTC8(timeStamp) {
    const now = timeStamp ? timeStamp : Date.now();
    const utc8Offset = 8 * 60 * 60 * 1000; // 东八区的时区偏移量，单位为毫秒
    const utc8Time = now + utc8Offset;
    return utc8Time;
  },

  // 判断Json是否为空
  isEmptyObject(data) {
    let arr = Object.keys(data);
    return arr.length == 0
  },

  //json数组里面的某一个字段是否等于一个变量
  isFieldEqual(arr, field, value) {
    return arr.some(item => item[field] == value);
  },

  //数组里面的某一个字段等于一个变量，则返回数组里面他对应的下标
  findIndexByField(arr, field, value) {
    return arr.findIndex(item => item[field] == value);
  },

  //判断json里面的键名是否都有值
  checkValues(obj) {
    return Object.values(obj).every(value => value !== undefined && value !== null && value !== '');
  },

  //json里面键名有值得取出来重新组成一个json
  extractValidKeys(json) {
    // 创建一个新的JSON对象
    const result = {};
    // 遍历JSON对象的每一个键
    for (let key in json) {
      // 获取当前键对应的值
      const value = json[key];

      // 判断值的类型
      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        // 如果值是一个对象，则递归调用该方法
        const extractedValue = this.extractValidKeys(value);

        // 如果递归调用返回的结果不为空，则将键值对添加到新的JSON对象中
        if (Object.keys(extractedValue).length > 0) {
          result[key] = extractedValue;
        }
      }
      else if (this.isJsonArray(value) == "arr" && value.length) {  //数组
        //console.log("空数组是走到你这里2")
        result[key] = value;
      }
      else if (this.isString(value) && value) {  //字符串
        //console.log("空数组是走到你这里3", value)
        // 如果值不是对象且不为空，则将键值对添加到新的JSON对象中
        result[key] = value;
      } else if (this.isNumber(value) || value === 0) { //数字
        result[key] = value;
      } else {
        //console.log("空数组是走到你这里45", value)
      }
    }

    return result;
  },

  //拼接url
  buildUrl(base, queries) {
    let ret = base
    if (typeof (queries) == 'undefined') return ret
    let isFirst = true
    for (let key in queries) {
      let value = queries[key]
      if (isFirst) {
        ret += '?'
        isFirst = false
      } else {
        ret += '&'
      }
      if (typeof (value) == 'undefined' || value === null) {
        ret += key
      } else {
        // ret += key + '=' + encodeURIComponent(value)
        ret += key + '=' + value
      }
    }
    return ret
  },

  //多维数组得深拷贝
  deepcopy(obj) {
    return JSON.parse(JSON.stringify(obj))
  },

  //时间转时间戳
  getTimeFn(t) {
    if (t) {
      return new Date(t.replace(/-/g, "/")).getTime()
    } else {
      return new Date().getTime()
    }
  },

  // 数组去重
  unique(arr) {
    return [...new Set(arr)]
  },

  //判断是不是数字
  isNumber(val) {
    return typeof val === 'number' && Number.isFinite(val);
  },


  // js数组根据对象中的元素去重
  arrayUnique2(arr, name) {
    var hash = {};
    return arr.reduce(function (item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
      return item;
    }, []);
  },

  //传入id和parentId，如果parentId=别人的id，则加到别人的children里面
  transformArray(arr, id, pid) {
    const map = {};
    const roots = [];
    arr.forEach(item => {
      map[item[id]] = { ...item, children: [] };
    });
    arr.forEach(item => {
      if (item[pid] && map[item[pid]]) {
        map[item[pid]].children.push(map[item[id]]);
      } else {
        roots.push(map[item[id]]);
      }
    });
    return roots;
  },

  //字段排序
  sortItems(items: Item[], sortOrder: "asc" | "desc", field): Item[] {
    return items
      .sort((a, b) => {
        if (sortOrder === "asc") {
          return a[field] - b[field];
        } else {
          return b[field] - a[field];
        }
      })
      .map((item) => {
        if (item.children) {
          item.children = this.sortItems(item.children, sortOrder, field);
        }
        return item;
      });
  },

  // 获取最后一个斜杠后面的内容
  substringFn(str) {
    const lastIndex = str.lastIndexOf("/");
    const result = str.substring(lastIndex + 1);
    return result
  },

  //判断是不是字符串
  isString(str) {
    return (typeof str == 'string') && str.constructor == String;
  },

  //第一个对象取值 给第二个对象赋值
  formatFunction(param1, param2) {
    Object.keys(param2).forEach(function (v) {
      if (Object.prototype.hasOwnProperty.call(param1, v)) {
        param2[v] = param1[v];
      }
    });
    return param2;
  },

  //两数组比较,取相同的值组成新的数组
  getCommonElements(arr1, arr2) {
    if (!arr1.length && arr2.length) return arr2
    if (arr1.length && !arr2.length) return arr1
    return arr1.filter(item => arr2.includes(item));
  },

  //两数组比较,取相同的值组成新的数组(如果其中有一个数组为空，则返回空数组）
  getCommonElements2(arr1, arr2) {
    if (arr1.length === 0 || arr2.length === 0) return [];
    return arr1.filter(item => arr2.includes(item));
  },

  //传入两个数组，取不同的值组成新数组
  getDifferentValues(arr1, arr2) {
    // 过滤出 arr1 中不在 arr2 中的值
    const uniqueToArr1 = arr1.filter(item => !arr2.includes(item));
    // 过滤出 arr2 中不在 arr1 中的值
    const uniqueToArr2 = arr2.filter(item => !arr1.includes(item));
    // 合并两个结果
    return uniqueToArr1.concat(uniqueToArr2);
  },

  //根据数组对象中相同属性值组建新数组
  sameSortArr(beforeData, name) {
    let afterData = <any>[];
    let tempArr = [];
    for (let i = 0; i < beforeData.length; i++) {
      if (tempArr.indexOf(beforeData[i][name]) == -1) {
        afterData.push({
          name: beforeData[i][name],
          origin: [beforeData[i]]
        });
        tempArr.push(beforeData[i][name]);
      } else {
        for (let j = 0; j < afterData.length; j++) {
          if (afterData[j].name == beforeData[i][name]) {
            afterData[j].origin.push(beforeData[i]);
            break;
          }
        }
      }
    }
    return afterData
  },

  //两数组比较，取不同的值组成新的数组
  takeNewArray(arr1, arr2) {
    const set1 = new Set(arr1);
    const set2 = new Set(arr2);
    const combinedSet = new Set([...set1, ...set2]);
    const differenceSet = new Set([...combinedSet].filter(item => !set1.has(item) || !set2.has(item)));
    return [...differenceSet];
  },

  //把一个数组拆分成几个数组
  splitArray(array, chunkSize) {
    const result = [];
    for (let i = 0; i < array.length; i += chunkSize) {
      result.push(array.slice(i, i + chunkSize));
    }
    return result;
  },

  //根据秒，解析出时分秒
  formatTime(seconds) {
    var hours = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds % 3600) / 60);
    var secs = seconds % 60;
    return { hours, minutes, secs }
  },

  //身份证是否正确
  async isIdCard(idCard) {
    let resp = await cloud.fetch({
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      method: 'POST', url: "https://shenfenzheng.293.net/ids.php", data: {
        q: idCard
      }
    })
    if (resp.data.includes("对不起")) {
      return false
    } else {
      return true
    }
  },

  //判断变量的数据类型
  isJsonArray(variable) {
    if (typeof variable === "string") {
      return "string";
    } else if (Array.isArray(variable)) {
      // 进一步判断是否为JSON数组
      let isJsonArray = variable.every(item => typeof item === "object" && item !== null && Object.keys(item).length > 0);
      if (isJsonArray) {
        return "jsonArr";
      } else {
        return "arr";
      }
    } else {
      return "not a string, array, or json array";
    }
  },


  //laf 的相关操作方法

  //生成 token
  generateToken(userId) {
    let now = Date.now()
    const payload = {
      uid: userId,
      exp: Math.floor(now / 1000) + 60 * 60 * 24 * 90,
    }
    return cloud.getToken(payload)
  },

  //模糊查询
  fuzzyQuery(userWhereJson) {
    if (this.isEmptyObject(userWhereJson)) return {}
    userWhereJson = this.extractValidKeys(this.deepcopy(userWhereJson))//只要有值的部分
    delete userWhereJson.pageIndex
    delete userWhereJson.pageSize
    for (let key in userWhereJson) {
      let item = userWhereJson[key]
      if (item) {
        if (this.isString(item)) {
          item = item.trim()
          //模糊搜索
          userWhereJson[key] = { $regex: item, $options: "i" }
        } else if (this.isJsonArray(item) == "arr") {
          userWhereJson[key] = { $in: item }
        } else if (this.isNumber(item) || item == 0) {
          userWhereJson[key] = item
        }
      }
    }
    return userWhereJson
  },

  //新增数据库数据
  async addData(dbName, dataJson) {
    await cloud.nw.db.add({
      dbName,
      dataJson,
      cancelAddTime: false
    });
    return cloud.utils.requestReturn({ data: "" })
  },

  //更新数据库数据
  async updateData(dbName, data) {
    let dataJson = this.deepcopy(data)
    delete dataJson._id
    let resp = await cloud.nw.db.update({ dbName, whereJson: { _id: data._id }, dataJson });
    console.log("修改后的值", resp)
    return cloud.utils.requestReturn({ data: "" })
  },

  //删除数据库数据
  async deleteData(dbName, whereJson) {
    await cloud.nw.db.del({ dbName, whereJson });
    return cloud.utils.requestReturn({ data: "" })
  },

  //查询某一个数据库数据
  async findOne(dbName, whereJson) {
    const res = await db.collection(dbName).findOne(whereJson)
    return cloud.utils.requestReturn({ data: res })
  },

  //查询某一个数据库数据
  async findData(dbName, whereJson, fieldJson = {}) {
    let res = await cloud.nw.db.findByWhereJson({ dbName, whereJson, fieldJson })
    return cloud.utils.requestReturn({ data: res })
  },

  //数据返回
  requestReturn(query) {
    //code 正常：200
    let obj = { code: 200, data: "", msg: "操作成功" }
    if (query.hasOwnProperty("code")) obj.code = query.code
    if (query.hasOwnProperty("msg")) obj.msg = query.msg
    if (query.hasOwnProperty("data")) obj.data = query.data
    return obj
  },


  //获取存储筒文件名
  getFileName(str) {
    // 使用split()方法将字符串按照/分割成数组
    const parts = str.split('/');
    // 使用pop()方法获取数组最后一个元素
    const lastPart = parts.pop();
    return lastPart;
  },


  //删除存储桶里面的文件
  async ossDel(bucketName, url) {
    let name = this.getFileName(url)

    // 获取存储桶
    const bucket = cloud.storage.bucket(bucketName)
    // 获取文件列表
    const res = await bucket.listFiles()
    let info = this.isFieldEqual(res.Contents, "Key", name)
    if (!info) return
    // 删除文件
    await bucket.deleteFile(name)
  },
}


